<template>
	<view class="profile-container">
		<!-- 顶部导航栏 -->
		
		<!-- 头像设置 -->
		<view class="profile-item" @click="chooseAvatar">
			<view class="item-label">头像</view>
			<view class="item-content">
				<image class="avatar" :src="form.avatar || defaultAvatar" mode="aspectFill"></image>
				<text class="icon-arrow-right">›</text>
			</view>
		</view>
		
		<!-- 昵称设置 -->
		<view class="profile-item">
			<view class="item-label">昵称</view>
			<view class="item-content">
				<input 
					class="input-text" 
					type="text" 
					v-model="form.name" 
					placeholder="请输入昵称"
					maxlength="20"
				/>
			</view>
		</view>
		
		<!-- 性别设置 -->
		<view class="profile-item" @click="showGenderPicker">
			<view class="item-label">性别</view>
			<view class="item-content">
				<text class="input-text">{{ genderText }}</text>
				<text class="icon-arrow-right">›</text>
			</view>
		</view>
		
		<!-- 手机号设置 -->
		<view class="profile-item">
			<view class="item-label">手机号</view>
			<view class="item-content">
				<input 
				    disabled
					class="input-text" 
					type="number" 
					v-model="form.phone" 
					placeholder="请输入手机号"
					maxlength="11"
				/>
				<button 
					class="get-phone-btn" 
					open-type="getPhoneNumber" 
					@getphonenumber="getPhoneNumber"
				>
					获取手机号
				</button>
			</view>
		</view>
		
		<!-- 个人简介 -->
		<view class="profile-section">
			<view class="section-label">个人简介：</view>
			<view class="textarea-container">
				<textarea 
					class="textarea" 
					v-model="form.note" 
					placeholder="写点什么介绍一下自己吧..."
					maxlength="200"
					:show-confirm-bar="false"
				></textarea>
			</view>
		</view>
		
		<!-- 个人照片上传 -->
		<view class="profile-section">
			<view class="section-label">可上传个人照片：</view>
			<view class="photo-grid">
				<view 
					v-for="(photo, index) in form.photos" 
					:key="getPhotoKey(photo, index)" 
					class="photo-item"
					@click="previewPhoto(index)"
				>
					<image :src="getPhotoUrl(photo)" mode="aspectFill" class="photo-image"></image>
					<view class="photo-delete" @click.stop="deletePhoto(index)">×</view>
				</view>
				<view 
					v-if="(form.photos?.length || 0) < maxPhotos" 
					class="photo-add" 
					@click="choosePhotos"
				>
					<text class="add-icon">📷</text>
				</view>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-button" @click="saveProfile" :class="{ disabled: saving }">
			<text class="save-text">{{ saving ? '保存中...' : '保存' }}</text>
		</view>
		
		<!-- 性别选择弹窗 -->
		<view v-if="showGender" class="modal-overlay" @click="hideGenderPicker">
			<view class="modal-content" @click.stop>
				<view class="modal-title">选择性别</view>
				<view class="gender-options">
					<view 
						v-for="option in genderOptions" 
						:key="option.value"
						class="gender-option"
						:class="{ active: form.gender === option.value }"
						@click="selectGender(option.value)"
					>
						{{ option.label }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { uploadFile, post } from '@/common/api.js'
import { showDialog } from '@/common/util.js'
import { one } from '@/common/data.js'

// 响应式数据
const form = ref({
	avatar: '',
	name: '',
	gender: 1, // 1-男, 2-女, 0-未设置
	phone: '',
	note: '',
	photos: []
})

const showGender = ref(false)
const saving = ref(false)
const maxPhotos = 9
const defaultAvatar = '/static/logo.png'

// 性别选项
const genderOptions = [
	{ label: '男', value: 1 },
	{ label: '女', value: 2 },
	{ label: '不设置', value: 0 }
]

// 计算属性
const genderText = computed(() => {
	const option = genderOptions.find(item => item.value === form.value.gender)
	return option ? option.label : '请选择'
})

// 页面加载时获取用户资料
onMounted(async () => {
	await loadUserProfile()
})

// 加载用户资料
const loadUserProfile = async () => {
	try {
		const res = await one('current_user_all', {})
		if (res.code === 200 && res.data) {
			form.value = {
				avatar: res.data.avatar || '',
				name: res.data.name || '',
				gender: res.data.gender || 1,
				phone: res.data.phone || '',
				note: res.data.note || res.data.description || '',
				photos: res.data.photos || []
			};
		}
	} catch (error) {
		console.error('加载用户资料失败:', error)
	}
}

// 返回上一页
const goBack = () => {
	uni.navigateBack()
}

// 选择头像
const chooseAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0]
			await uploadAvatar(tempFilePath)
		},
		fail: (error) => {
			showDialog('选择图片失败')
		}
	})
}

// 上传头像
const uploadAvatar = async (filePath) => {
	uni.showLoading({ title: '上传中...' })
	try {
		const res = await uploadFile(filePath)
		if (res.code === 200) {
			form.value.avatar = res.data.url
			uni.hideLoading()
			uni.showToast({ title: '头像上传成功', icon: 'success' })
		} else {
			uni.hideLoading()
			showDialog(res.msg)
		}
	} catch (error) {
		uni.hideLoading()
		showDialog('头像上传失败')
	}
}

// 显示性别选择器
const showGenderPicker = () => {
	showGender.value = true
}

// 隐藏性别选择器
const hideGenderPicker = () => {
	showGender.value = false
}

// 选择性别
const selectGender = (value) => {
	form.value.gender = value
	hideGenderPicker()
}

// 选择照片
const choosePhotos = () => {
	const remainCount = maxPhotos - (form.value.photos?.length || 0)
	uni.chooseImage({
		count: remainCount,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			for (let filePath of res.tempFilePaths) {
				await uploadPhoto(filePath)
			}
		},
		fail: (error) => {
			showDialog('选择图片失败')
		}
	})
}

// 上传照片
const uploadPhoto = async (filePath) => {
	uni.showLoading({ title: '上传中...' })
	try {
		const res = await uploadFile(filePath)
		console.log(res)
		if (res.code === 200) {
			if (!form.value.photos) {
				form.value.photos = []
			}
			// 新增的照片只保存 URL，没有 ID
			form.value.photos.push(res.data.url)
			uni.hideLoading()
		} else {
			uni.hideLoading()
			showDialog(res.msg)
		}
	} catch (error) {
		console.log("上传失败")
		uni.hideLoading()
		showDialog('照片上传失败')
	}
}

// 获取照片的唯一标识
const getPhotoKey = (photo, index) => {
	// 如果是对象格式且有 id，使用 id 作为 key
	if (typeof photo === 'object' && photo.id) {
		return photo.id
	}
	// 否则使用索引
	return index
}

// 获取照片 URL
const getPhotoUrl = (photo) => {
	// 如果是对象格式，返回 url 属性
	if (typeof photo === 'object' && photo.url) {
		return photo.url
	}
	// 如果是字符串，直接返回
	return photo
}

// 预览照片
const previewPhoto = (index) => {
	const urls = form.value.photos.map(photo => getPhotoUrl(photo))
	uni.previewImage({
		current: index,
		urls: urls
	})
}

// 删除照片
const deletePhoto = (index) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这张照片吗？',
		success: (res) => {
			if (res.confirm) {
				form.value.photos.splice(index, 1)
			}
		}
	})
}

// 获取微信手机号
const getPhoneNumber = async (e) => {
	console.log('获取手机号事件:', e)
	
	if (e.detail.errMsg === 'getPhoneNumber:ok') {
		// 用户同意授权
		const { code } = e.detail
		
		try {
			uni.showLoading({ title: '获取中...' })
			
			// 调用后端接口解密手机号
			const res = await post('/customer/phone', {
				code: code,
				config:"wxapp"
			})
			
			uni.hideLoading()
			
			if (res.code === 200 && res.data) {
				form.value.phone = res.data
				uni.showToast({ 
					title: '手机号获取成功', 
					icon: 'success' 
				})
			} else {
				showDialog(res.msg || '获取手机号失败')
			}
		} catch (error) {
			uni.hideLoading()
			console.error('获取手机号失败:', error)
			showDialog('获取手机号失败，请重试')
		}
	} else {
		// 用户拒绝授权
		showDialog('需要授权才能获取手机号')
	}
}

// 保存资料
const saveProfile = async () => {
	if (saving.value) return
	
	// 基本验证
	if (!form.value.name || !form.value.name.trim()) {
		showDialog('请输入昵称')
		return
	}
	
	if (form.value.phone && !/^1[3-9]\d{9}$/.test(form.value.phone)) {
		showDialog('请输入正确的手机号')
		return
	}
	
	saving.value = true
	uni.showLoading({ title: '保存中...' })
	
	try {
		// 处理照片数据格式
		const photosData = form.value.photos.map(photo => {
			// 如果是对象格式（有 id 的老照片），保持原格式
			if (typeof photo === 'object' && photo.id) {
				return photo
			}
			// 如果是字符串（新增的照片），转换为对象格式
			return { url: photo }
		})
		
		const res = await post('/customer/updateExt', {
			avatar: form.value.avatar,
			name: (form.value.name || '').trim(),
			gender: form.value.gender,
			phone: form.value.phone,
			note: (form.value.note || '').trim(),
			photos: photosData
		})
		
		uni.hideLoading()
		
		if (res.code === 200) {
			uni.showToast({ title: '保存成功', icon: 'success' })
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			showDialog(res.msg || '保存失败')
		}
	} catch (error) {
		uni.hideLoading()
		showDialog('保存失败，请重试')
	} finally {
		saving.value = false
	}
}
</script>

<style scoped>
.profile-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 30rpx;
}

/* 导航栏样式 */
.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	background-color: #e5e5e5;
	padding: 0 30rpx;
	position: relative;
}

.nav-back {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-arrow {
	font-size: 40rpx;
	color: #333;
	font-weight: bold;
}

.nav-title {
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.nav-menu {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-menu {
	font-size: 36rpx;
	color: #333;
	font-weight: bold;
}

/* 资料项样式 */
.profile-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 2rpx;
}

.item-label {
	font-size: 32rpx;
	color: #333;
	width: 120rpx;
}

.item-content {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: flex-end;
}

.input-text {
	font-size: 32rpx;
	color: #333;
	text-align: right;
	flex: 1;
}

.input-text::placeholder {
	color: #ccc;
}

.icon-arrow-right {
	font-size: 32rpx;
	color: #ccc;
	margin-left: 20rpx;
}

/* 获取手机号按钮样式 */
.get-phone-btn {
	margin-left: 20rpx;
	padding: 10rpx 20rpx;
	background-color: #AA0E99;
	color: #fff;
	font-size: 24rpx;
	border-radius: 20rpx;
	border: none;
	line-height: 1.2;
	min-width: 120rpx;
}

/* 头像样式 */
.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	margin-right: 20rpx;
}

/* 区块样式 */
.profile-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-label {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 20rpx;
}

/* 文本域样式 */
.textarea-container {
	border: 2rpx solid #e5e5e5;
	border-radius: 10rpx;
	padding: 20rpx;
}

.textarea {
	width: 100%;
	min-height: 200rpx;
	font-size: 30rpx;
	color: #333;
	line-height: 1.5;
}

.textarea::placeholder {
	color: #ccc;
}

/* 照片网格样式 */
.photo-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.photo-item {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	border-radius: 10rpx;
	overflow: hidden;
}

.photo-image {
	width: 100%;
	height: 100%;
}

.photo-delete {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	background-color: rgba(0, 0, 0, 0.6);
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
}

.photo-add {
	width: 200rpx;
	height: 200rpx;
	border: 2rpx dashed #ccc;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fafafa;
}

.add-icon {
	font-size: 60rpx;
	color: #ccc;
}

/* 保存按钮样式 */
.save-button {
	margin: 60rpx 30rpx 30rpx;
	height: 88rpx;
	background-color: #AA0E99;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.save-button.disabled {
	background-color: #ccc;
}

.save-text {
	font-size: 32rpx;
	color: #fff;
	font-weight: 500;
}

/* 模态框样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
}

.modal-content {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	width: 80%;
	max-width: 600rpx;
}

.modal-title {
	font-size: 36rpx;
	font-weight: 500;
	text-align: center;
	margin-bottom: 40rpx;
	color: #333;
}

.gender-options {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.gender-option {
	padding: 24rpx;
	text-align: center;
	font-size: 32rpx;
	border-radius: 10rpx;
	background-color: #f5f5f5;
	color: #333;
}

.gender-option.active {
	background-color: #AA0E99;
	color: #fff;
}
</style>
